package study.chapter03.stream;

import java.io.*;

public class TestIOStream {
    private static String fileName = "F:/0temp/hello3.txt";
    public static void main(String[] args) throws IOException {
        //向磁盘写入文件
        output();
        //从磁盘读取文件
        input();
    }

    //向磁盘写入文件
    public static void output() throws IOException {
        File file = new File(fileName);
        FileOutputStream fos = null;
        OutputStreamWriter writer = null;
        try {
            fos = new FileOutputStream(file);
            writer = new OutputStreamWriter(fos, "UTF-8");
            //写第一句
            writer.append("我爱java");
            //换行
            writer.append("\r\n");
            //写第二句
            writer.append("java牛逼！");
            writer.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            writer.close();
            fos.close();
        }
    }

    //从磁盘读取文件
    public static void input() throws IOException{
        InputStream is = null;
        InputStreamReader reader = null;
        try {
            is = new FileInputStream(fileName);
            reader = new InputStreamReader(is, "UTF-8");
            StringBuffer buffer = new StringBuffer();
            while (reader.ready()){
                buffer.append((char)reader.read());
            }
            System.out.println(buffer.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            reader.close();
            is.close();
        }

    }
}
